package com.twb.netty.handler;

import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @ClassName NettyChannelHandlerPool 
 * @Description 通道组池，管理所有websocket连接
 * @author DHL
 * @date 2021年7月8日 上午9:43:02
 */
public class NettyChannelHandlerPool {

	protected static Logger log = LoggerFactory.getLogger(NettyChannelHandlerPool.class);

	/**
	 * 全员广播
	 */
	private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	/**
	 * 按照项目分组广播
	 */
	private static ConcurrentHashMap<String, ChannelGroup> channelGroupMap = new ConcurrentHashMap<String, ChannelGroup>();
	

	protected static void add(Channel channel) {
		add(channel, null);
	}

	protected static void add(Channel channel, String group) {
		if (StringUtils.isBlank(group)) {
			channelGroup.add(channel);
		} else {
			ChannelGroup t_channelGroup = null;
			if (channelGroupMap.containsKey(group)) {
				t_channelGroup = channelGroupMap.get(group);
			} else {
				t_channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
				channelGroupMap.put(group, t_channelGroup);
			}
			t_channelGroup.add(channel);
		}
	}
	
	
	/**
	 * @Title remove
	 * @Description 删除通道
	 * @param channel
	 * @author DHL
	 * @date 2021年7月8日 上午9:55:31
	 */
	protected static void remove(Channel channel) {
		remove(channel, null);
	}

	protected static void remove(Channel channel, String group) {
		if (StringUtils.isBlank(group)) {
			channelGroup.remove(channel);
		} else if (channelGroupMap.containsKey(group)) {
			ChannelGroup t_channelGroup = channelGroupMap.get(group);
			t_channelGroup.remove(channel);
		}
	}
	
	
	protected static void writeAndFlush(String message) {
		writeAndFlush(message, null);
	}
	
	
	protected static void writeAndFlush(String message, String group) {
		if (StringUtils.isBlank(group)) {
			channelGroup.writeAndFlush(new TextWebSocketFrame(message));
		} else if (channelGroupMap.containsKey(group)) {
			ChannelGroup t_channelGroup = channelGroupMap.get(group);
			t_channelGroup.writeAndFlush(new TextWebSocketFrame(message));
		}
	}

}
